#include "common.h"
#include "Timestamp.h"
#include "Streams.h"

using namespace esda;

int stringToInt(string s)
{
	istringstream istr(s);
	int i;
	istr >> i;
	return i;
}

int main(int argc, char **argv)
{
	if (argc != 2) {
		DEBUG("Wrong number of arguments (" << argc << " found)\nUsage: " << argv[0] << " DATABASE");
		
		return 1;
	}
	
	string
		databaseName(argv[1]),
		requestStreamName("apacheLog_request"),
		answerStreamName("apacheLog_answer"),
		requetesProchesViewName("requetesProches"),
		requetePrecedenteViewName("requetePrecedente"),
		ligne;
	
	SQLiteStream<string> requestStream(databaseName, requestStreamName);
	SQLiteStream<double> answerStream(databaseName, answerStreamName);
	
	Timestamp t;
	
	// On affiche l'intervalle de temps des logs
	
	t = requestStream.getLastEnd();
	
	DEBUG("stream.getFirstStart() = " << requestStream.getFirstStart());
	DEBUG("stream.getLastEnd() = " << t);
	
	// SQLOperatorStream(
	// 	const string& databaseName,
	// 	const string& viewName,
	// 	const string& idClause,
	// 	const string& startTimeClause,
	// 	const string& endTimeClause,
	// 	const string& valueClause,
	// 	const string& fromClause,
	// 	const string& whereClause);
	SQLOperatorStream<string> requetesProches(
		databaseName,
		requetesProchesViewName,
		requestStreamName + ".Id",
		requestStreamName + ".StartTime",
		requestStreamName + ".EndTime",
		requestStreamName + ".Value",
		requestStreamName
			+ " LEFT JOIN " + answerStreamName
			+ " ON " + answerStreamName + ".StartTime = " + requestStreamName + ".StartTime",
		answerStreamName + ".Value = 200 AND EXISTS (SELECT innerStream.Value FROM " + requestStreamName + " AS innerStream WHERE innerStream.StartTime < " + requestStreamName + ".StartTime AND innerStream.StartTime >= " + requestStreamName + ".StartTime - 5)");
	
	SQLOperatorStream<string> requetePrecedente(
		databaseName,
		requetePrecedenteViewName,
		"innerStream.Id",
		requestStreamName + ".StartTime",
		requestStreamName + ".EndTime",
		"innerStream.Value",
		requestStreamName + ", " + requestStreamName + " AS innerStream",
		"innerStream.StartTime < " + requestStreamName + ".StartTime AND innerStream.StartTime >= " + requestStreamName + ".StartTime - 5");
	
	DEBUG(" Basic streams end time : " << t);
	
	t = requetesProches.getFirstStart();
	Timestamp endTime = requetesProches.getLastEnd();
	
	DEBUG(" StartTime for correlation query : " << t);
	
	while (t < endTime) {
		string aQueryRetrievedValue = requetesProches.get(t);

		string theRelevantPage = requetePrecedente.get(t);

		DEBUG(" Retrieved for time " << t << " : '" << aQueryRetrievedValue << "' was called just after '" << theRelevantPage << "'");
		
		t = requetesProches.getNextStart(t + 1);
	}
	
	int blah;
	
	cin >> blah;
	
	return 0;
}
